import { Component, OnInit, OnDestroy, ViewChild, ElementRef, Compiler, ViewContainerRef, ComponentRef, Renderer, NgModule, EventEmitter } from "@angular/core";
import { Location } from "@angular/common";
import { DomSanitizer, BrowserModule, SafeResourceUrl } from "@angular/platform-browser";
import { Router, RouterState, ActivatedRoute, NavigationEnd } from "@angular/router";
import { Subject } from "rxjs/Subject";
import { ReplaySubject } from "rxjs/ReplaySubject";
import { Observable } from "rxjs/Observable";
import { Http } from "@angular/http";

import { CommentsService } from "./comments.service";
import "rxjs/add/operator/switchMap";
import { UserService } from "user";

interface ColumnType {
  column_key: string;
  column_name: string;
  categories: [CategoryType];
}

interface CategoryType {
  category_key: string;
  category_name: string;
  granted: number;
}

interface ArticleType {
  is_grouping?: number;
  category_key: string;
  group_id?: string;
  group_name?: string;
  summary?: string;
  poster?: string;
  group_articles: ArtcicleGroup[];
}

interface ArtcicleGroup {
  detail_id: string;
  column_name: string;
  category_key: string;
  category_name?: string;
  title: string;
  summary?: string;
  media_type: string;
  source_url: string;
  thumb_cdn_url: string;
  thumb_local_url?: string;
  access_level: string;
  add_time: string;
  file_size?: number;
}

interface AdType {
  ad_id: string;
  title: string;
  poster_url: string;
  jump_url: string;
  start_time: string;
  end_time: string;
}

@Component({
  selector: "comments",
  templateUrl: "comments.component.html",
  styleUrls: ["comments.component.less"]
})
export class CommentsComponent implements OnInit {
  DPFXCategories: CategoryType[];
  articles: ArticleType[];
  selectedCategory: CategoryType;
  articlesGroupOfSelectedCategory: ArticleType[];

  articlesGroupOfAllCategory: ArticleType[]; // 全部栏目中的列表
  ads: AdType[]; // 广告列表
  currentPic: number = 0;
  timer = <any>(1);

  selectedArticle: ArtcicleGroup;
  url: SafeResourceUrl;

  category: string;
  startTime: string = "";
  limit: number = 10;
  tabNo: string = "dapanfenxi";

  changeAll: boolean = true;
  timeoutId = <any>(1);
  @ViewChild("loadTracker") loadTracker: ElementRef;
  @ViewChild("newList") newList: ElementRef;

  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private commentsService: CommentsService,
    private userService: UserService,
    private http: Http,
    private renderer: Renderer,
    private compiler: Compiler,
    private sanitizer: DomSanitizer,
    private location: Location
  ) { }
  
  ngOnInit() {
    this.userService.loginStatusSub.subscribe((status) => {
      if (status) {
        this.getDPFXArticles();
        this.getDPFXArticlesOfAllCategory();
        this.getAds();
      } else {
        this.clearObjects();
        if (this.userService.currentModal !== "bindMobile") {
          this.userService.setModal("login");
        }
      }
    });
    this.userService.tokenSub.subscribe((str) => {
      if (str === "Token") {
        this.getDPFXArticles();
        this.getDPFXArticlesOfAllCategory();
        this.getAds();
        this.userService.setModal("hide");
      }
    });
    // if ( !this.userService.isLogined && !this.userService.isToken ) {
    //   // if (this.GetQueryString("code") !== null && this.GetQueryString("state") !== null) {
    //   //   // console.log(123);
    //   //   // this.userService.setModal("bindMobile");
    //   //   this.userService.setModal("bindMobile");
    //   // } else if( !this.userService.isToken ) {
    //     this.userService.setModal("login");
    //   // }
    // }
  }

  clearObjects() {
    this.DPFXCategories = null;
    this.articlesGroupOfAllCategory = null;
    this.articles = null;
    this.selectedCategory = null;
    this.articlesGroupOfSelectedCategory = null;
    this.ads = null;
    
    this.selectedArticle = null;
    this.url = null;
  } 

  private getDPFXArticles() {
    this.commentsService.getDPFXArticles().subscribe(data => {
      if (data.code === 0 && data.msg === "success" ) {
        this.DPFXCategories = this.getCategories(data.data.columns, "dapanfenxi");
        this.articles = data.data.articles;
      } else if(data.code === 1002 && data.msg === "Expired token") {
        this.userService.updateLogStatus(false);
        this.userService.setModal("login");
      }
    });
  }

  private getCategories(columns: ColumnType[], columenName: string) {
    for ( let i = 0 ; i < columns.length ; i ++ ) {
      if (columns[i].column_key === columenName) {
        return columns[i].categories;
      }
    }
  }

  private getDPFXArticlesOfAllCategory() {
    this.commentsService.getDPFXArticlesOfAllCategory().subscribe(data => {
      if (data.code === 0 && data.msg === "success") {
        this.articlesGroupOfAllCategory = data.data.articles;
        //console.log(data.data.articles);
        this.selectedArticle = this.articlesGroupOfAllCategory[0].group_articles[0];
        this.url = this.sanitizer.bypassSecurityTrustResourceUrl(this.selectedArticle.source_url);
      } else if(data.code === 1002 && data.msg === "Expired token") {
        this.userService.updateLogStatus(false);
        this.userService.setModal("login");
      }
    });
  }

  private getAds() {
    this.commentsService.getAds().subscribe(data => {
      if (data.code === 0 && data.msg === "success") {
        this.ads = data.data;
      } else if(data.code === 1002 && data.msg === "Expired token") {
        this.userService.updateLogStatus(false);
        this.userService.setModal("login");
      }
    });
  }

  onClickCategory(category: CategoryType) {
    this.newList.nativeElement.scrollTop = 0;
    this.changeAll = false;
    this.startTime = "";
    this.selectedCategory = category;
    this.category = this.selectedCategory.category_key;
    this.articlesGroupOfSelectedCategory = [];
    this.articlesGroupOfSelectedCategory = this.getArticlesOfSelectedCategory(category.category_key);
    if (this.articlesGroupOfSelectedCategory.length < 1) {
      let nullArticle:ArticleType = {
          category_key:this.category,
          group_articles:[]
      };
      nullArticle.category_key = this.category
      this.articlesGroupOfSelectedCategory[0] = nullArticle;
      this.getArticleList();
    } else {
      this.selectedArticle = this.articlesGroupOfSelectedCategory[0].group_articles[0];
      this.url = this.sanitizer.bypassSecurityTrustResourceUrl(this.selectedArticle.source_url);
    }
  }

  private getArticlesOfSelectedCategory(category_key: string) {
    let articles: ArticleType[] = [];
    for (let i = 0 ; i < this.articles.length ; i ++ ) {
      if (this.articles[i].category_key === category_key) {
        articles = articles.concat(this.articles[i]);
      }
    }
    if (articles.length > 0 && articles[0].is_grouping === 0 ) {
      this.startTime = articles[0].group_articles[articles[0].group_articles.length - 1].add_time;
    }
    return articles;
  }

  changeColumn(str: string) {
    if ( str === "all" ) {
      this.newList.nativeElement.scrollTop = 0;
      this.changeAll = true;
      this.startTime = "";
      this.selectedCategory = null;
      this.articlesGroupOfSelectedCategory = [];
      this.selectedArticle = this.articlesGroupOfAllCategory[0].group_articles[0];
      this.url = this.sanitizer.bypassSecurityTrustResourceUrl(this.selectedArticle.source_url);
    }
  }

  private getArticleList() {
    this.commentsService.getArticleList(this.startTime, this.limit, this.category, this.tabNo).subscribe(data => {
      if ( data.code === 0 && data.msg === "success" && data.data.length > 0) {
        this.articlesGroupOfSelectedCategory[0].group_articles = this.articlesGroupOfSelectedCategory[0].group_articles.concat(data.data[0].group_articles);
        this.startTime = this.articlesGroupOfSelectedCategory[0].group_articles[this.articlesGroupOfSelectedCategory[0].group_articles.length - 1].add_time;
        if (this.articlesGroupOfSelectedCategory[0].group_articles.length === data.data[0].group_articles.length) {
          this.selectedArticle = this.articlesGroupOfSelectedCategory[0].group_articles[0];
          this.url = this.sanitizer.bypassSecurityTrustResourceUrl(this.selectedArticle.source_url);
        }
      } else if(data.code === 1002 && data.msg === "Expired token") {
        this.userService.updateLogStatus(false);
        this.userService.setModal("login");
      } else {
        console.info("get ArticleList err: ", data.errors);
      }
    });
  }

  loadMore(e: WheelEvent) {
    if (this.isLoadMoreActive() && !this.changeAll) {
      clearTimeout(this.timeoutId);
      this.timeoutId = setTimeout(() => {
        this.getArticleList();
      }, 200);
    }
  }

  private isLoadMoreActive() {
    if (!this.loadTracker) return false;
    let loadTrackerElem: HTMLElement = this.loadTracker.nativeElement;
    let parentElem = loadTrackerElem.parentElement;
    let top = loadTrackerElem.getBoundingClientRect().top;
    let parentRect = parentElem.getBoundingClientRect();
    // console.debug('is load more active: ', parentRect.top, '<=', top, '<=', parentRect.bottom);
    return (top >= parentRect.top && top <= parentRect.bottom);
  }

  onClickArticle(article: ArtcicleGroup, e) {
    this.selectedArticle = article;
    this.url = this.sanitizer.bypassSecurityTrustResourceUrl(this.selectedArticle.source_url);
  }

  clickAd(ad: AdType) {
    this.selectedArticle = null;
    this.url = this.sanitizer.bypassSecurityTrustResourceUrl(ad.jump_url);
  }

  leftActive = false;
  rightActive = false;
  
  toggleLeftState() {
    this.leftActive = !this.leftActive;
  }

  toggleRightState() {
    this.rightActive = !this.rightActive;
  }

  // private startCount() {
  //   this.timer = setInterval(() => {
  //     if (this.currentPic < this.ads.length - 1) {
  //       this.currentPic = this.currentPic + 1;
  //     }else {
  //       this.currentPic = 0;
  //     }
  //   }, 3000);
  // }

  // changebanner(id) {
  //   // console.log(id);
  //   clearTimeout(this.timer);
  //   this.currentPic = id;
  //   this.startCount();
  // }

  // changeNext() {
  //   clearTimeout(this.timer);
  //   if (this.currentPic < this.ads.length - 1) {
  //     this.currentPic = this.currentPic + 1;
  //   } else {
  //     this.currentPic = 0;
  //   }
  //   // console.log(this.currentPic);
  //   this.startCount();
  // }

  // changePrev() {
  //   clearTimeout(this.timer);
  //   if (this.currentPic > 0) {
  //     this.currentPic = this.currentPic - 1;
  //   } else {
  //     this.currentPic = this.ads.length - 1;
  //   }
  //   // console.log(this.currentPic);
  //   this.startCount();
  // }

  private GetQueryString( name:string) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return r[2];
    return null;
  }
}